package org.com.ashen.service.service.smssendlogmanage.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.log4j.Logger;
import org.com.ashen.dal.dataobject.SmsReport;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.CustomSmsIdAndMobile;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.CustomSmsIdAndMobileAndContent;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.PersonalityParams;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.request.*;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.BalanceResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.MoResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.ReportResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.SmsResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.manage.dos.SmsReportDO;
import org.com.ashen.service.service.smssendlogmanage.sms.manage.smsreport.SmsReportServiceImpl;
import org.com.ashen.service.service.smssendlogmanage.sms.param.SmsSendResult;
import org.com.ashen.service.service.smssendlogmanage.sms.util.AES;
import org.com.ashen.service.service.smssendlogmanage.sms.util.GZIPUtils;
import org.com.ashen.service.service.smssendlogmanage.sms.util.JsonHelper;
import org.com.ashen.service.service.smssendlogmanage.sms.util.http.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YimeiSmsUtil {

	private static String appId = "3SDK-EMY-0130-NCRUL";// 请联系销售，或者在页面中 获取 appId
	private static String secretKey = "7D2239E40C2DFCC3";// 请联系销售，或者在页面中 获取 密钥
	private static String host = "http://bjksmtn.b2m.cn";// 请联系销售获取 接口地址
	private static String algorithm = "AES/ECB/PKCS5Padding";// 加密算法
	private static String encode = "UTF-8"; // 编码
	private static boolean isGzip = true; // 是否压缩

	private static Logger logger = Logger.getLogger(YimeiSmsUtil.class.getName());
	/**
	 * 获取余额
	 * 
	 * 是否压缩
	 */
	public static void getBalance() {
		BalanceRequest pamars = new BalanceRequest();
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/getBalance", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			BalanceResponse response = JsonHelper.fromJson(BalanceResponse.class, result.getResult());
			if (response != null) {
				System.out.println("result data : " + response.getBalance());
			}
		}
	}
 
	/**
	 * 获取状态报告
	 * 
	 * 是否压缩
	 */
	public static String getReport() {
		ReportRequest pamars = new ReportRequest();
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/getReport", isGzip, encode);
		if ("SUCCESS".equals(result.getCode())) {
			logger.error(result.getResult());
			ReportResponse[] response = JsonHelper.fromJson(ReportResponse[].class, result.getResult());
//			String aa = "[{\"smsId\":\"162893601940200134\",\"customSmsId\":\"0\",\"state\":\"DELIVRD\",\"desc\":\"成功\",\"mobile\":\"15800654037\",\"receiveTime\":\"2021-08-14 18:13:42\",\"submitTime\":\"2021-08-14 18:13:39\",\"extendedCode\":null}]";
//			ReportResponse[] response = JsonHelper.fromJson(ReportResponse[].class, aa);
			if (response != null) {
				for (ReportResponse d : response) {
					SmsReport smsReport = SmsReportDO.reportResponseToSmsReport(d);
					SmsReportServiceImpl.insert(smsReport);
				}
			}
		}
		return  "";
	}

	public static List<SmsReport> smsGetReport(String smsId) {
		List<SmsReport> smsReports = SmsReportServiceImpl.selectOneReport(smsId);
		return smsReports;
	}


	/**
	 * 获取上行
	 * 
	 * 是否压缩
	 */
	public static void getMo() {
		MoRequest pamars = new MoRequest();
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/getMo", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			MoResponse[] response = JsonHelper.fromJson(MoResponse[].class, result.getResult());
			if (response != null) {
				for (MoResponse d : response) {
					System.out.println("result data:" + d.getContent() + "," + d.getExtendedCode() + "," + d.getMobile() + "," + d.getMoTime());
				}
			}
		}
	}

	/**
	 * 发送单条短信
	 * 
	 * 是否压缩
	 */
	public static String setSingleSms( String content, String customSmsId, String extendCode, String mobile) {
		SmsSingleRequest pamars = new SmsSingleRequest();
		pamars.setContent(content);
		pamars.setCustomSmsId(customSmsId);
		pamars.setExtendedCode(extendCode);
		pamars.setMobile(mobile);
		System.out.println(JSON.toJSONString(pamars));
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendSingleSMS", isGzip, encode);
		logger.error(JSON.toJSONString(result));
		System.out.println(JSON.toJSONString(result));
		//{"code":"SUCCESS","result":"{\"smsId\":\"162919249554200275\",\"mobile\":\"13651949883\",\"customSmsId\":null}"}
		if ("SUCCESS".equals(result.getCode())) {
			SmsSendResult smsSendResult = JSON.parseObject(result.getResult(),SmsSendResult.class);
			return smsSendResult.getSmsId();
		}
		return "";
	}

	/**
	 * 发送批次短信
	 * 
	 * 是否压缩
	 */
	public static JSONArray setBatchOnlySms(String content, String extendCode, String[] mobiles) {
		SmsBatchOnlyRequest pamars = new SmsBatchOnlyRequest();
		pamars.setMobiles(mobiles);
		pamars.setExtendedCode(extendCode);
		pamars.setContent(content);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendBatchOnlySMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
//				List<String> smsids = new ArrayList<>();
				JSONArray smsids = new JSONArray();
				for (SmsResponse d : response) {
					smsids.add(d.getSmsId());
//					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}

				return smsids;
			}
			return null;
		}
		return null;
	}

	/**
	 * 发送批次短信
	 * 
	 * 是否压缩
	 */
	public static void setBatchSms(String content, String extendCode, CustomSmsIdAndMobile[] customSmsIdAndMobiles) {
		SmsBatchRequest pamars = new SmsBatchRequest();
		pamars.setSmses(customSmsIdAndMobiles);
		pamars.setExtendedCode(extendCode);
		pamars.setContent(content);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendBatchSMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 发送个性短信
	 * 
	 * 是否压缩
	 */
	public static void setPersonalitySms(String extendCode, CustomSmsIdAndMobileAndContent[] customSmsIdAndMobileAndContents) {
		SmsPersonalityRequest pamars = new SmsPersonalityRequest();
		pamars.setSmses(customSmsIdAndMobileAndContents);
		pamars.setExtendedCode(extendCode);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendPersonalitySMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 发送个性短信
	 * 
	 * 是否压缩
	 */
	public static void setPersonalityAllSms( PersonalityParams[] customSmsIdAndMobileAndContents) {
		SmsPersonalityAllRequest pamars = new SmsPersonalityAllRequest();
		pamars.setSmses(customSmsIdAndMobileAndContents);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendPersonalityAllSMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 公共请求方法
	 */
	public static ResultModel request(String appId, String secretKey, String algorithm, Object content, String url, final boolean isGzip, String encode) {
		Map<String, String> headers = new HashMap<String, String>();
		HttpRequest<byte[]> request = null;
		try {
			headers.put("appId", appId);
			headers.put("encode", encode);
			String requestJson = JsonHelper.toJsonString(content);
			System.out.println("result json: " + requestJson);
			byte[] bytes = requestJson.getBytes(encode);
			if (isGzip) {
				headers.put("gzip", "on");
				bytes = GZIPUtils.compress(bytes);
			}
			byte[] parambytes = AES.encrypt(bytes, secretKey.getBytes(), algorithm);
			HttpRequestParams<byte[]> params = new HttpRequestParams<>();
			params.setCharSet("UTF-8");
			params.setMethod("POST");
			params.setHeaders(headers);
			params.setParams(parambytes);
			params.setUrl(url);
			if (url.startsWith("https://")) {
				request = new HttpsRequestBytes(params, null);
			} else {
				request = new HttpRequestBytes(params);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		HttpClient client = new HttpClient();
		String code = null;
		String result = null;
		try {
			HttpResponseBytes res = client.service(request, new HttpResponseBytesPraser());
			if (res == null) {
				System.out.println("请求接口异常");
				return new ResultModel(code, result);
			}
			if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
				if (res.getHttpCode() == 200) {
					code = res.getHeaders().get("result");
					if (code.equals("SUCCESS")) {
						byte[] data = res.getResult();
						data = AES.decrypt(data, secretKey.getBytes(), algorithm);
						if (isGzip) {
							data = GZIPUtils.decompress(data);
						}
						result = new String(data, encode);
					}
				} else {
					System.out.println("请求接口异常,请求码:" + res.getHttpCode());
				}
			} else {
				System.out.println("请求接口网络异常:" + res.getResultCode().getCode());
			}
		} catch (Exception e) {
			System.out.println("解析失败");
			e.printStackTrace();
		}
		ResultModel re = new ResultModel(code, result);
		return re;
	}

	
}
